package com.gill.jwt.controller;

import com.gill.jwt.annotation.Login;
import com.gill.jwt.config.properties.JwtProperties;
import com.gill.jwt.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: my-utils-repo
 * @description:
 * @author: Gill
 * @create: 2021-03-22 12:48
 **/
@Slf4j
@RestController
@RequestMapping(value = "/jwt")
public class JwtController {

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/generateToken")
    public String generateToken(){
        // 登录成功,使用用户信息生成token
        Map userInfo = new HashMap(2);
        userInfo.put("userId",1);
        userInfo.put("username","gill");
        userInfo.put("role","role");
        String token = jwtUtil.generateToken(userInfo);
        return "登录成功,返回的token："+token;
    }

    @Login
    @GetMapping("/dosth")
    public String dosth(){
        Map<String,Object> result = new HashMap<>(3);
        HttpServletRequest request = getHttpServletRequest();
        result.put("userId",request.getAttribute("userId"));
        result.put("username",request.getAttribute("username"));
        result.put("role",request.getAttribute("role"));
        return "当前用户信息"+result.toString();
    }

    /**
     * 可以在任何地方获取到当前的Request对象
     */
    private HttpServletRequest getHttpServletRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }

}
